package acs.bridge.utility;

import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Properties;


/**
 * acs.utility
 * User: KuznetsovStV
 * Date: 19.02.12
 * Time: 12:07
 * for working with parameters
 */
public class UtilityParameters {

    static public Properties combineProperties(Properties properties1, Properties properties2) {

        if (properties2 != null) {
            Iterator it = properties2.keySet().iterator();

            if (properties1 == null)
                properties1 = new Properties();

            while (it.hasNext()) {
                String key = (String) it.next();
                if (!properties1.containsKey(key)) {
                    properties1.put(key, properties2.getProperty(key));
                }

            }
        }
        return properties1;
    }

    static public Properties getParamRaw(Connection connection, String commandLine
    ) throws SQLException {
        Properties l_prop = new Properties();


        // Создание объекта ARRAY.

        Object[] l_Record;

        StructDescriptor l_structDesc =
                StructDescriptor.createDescriptor("BRIDGE.T_PARAM", connection);
        ArrayDescriptor l_arrayDesc =
                ArrayDescriptor.createDescriptor("BRIDGE.TT_PARAM", connection);

        ARRAY l_array = new ARRAY(l_arrayDesc, connection, null);


        OracleCallableStatement cStatement = (OracleCallableStatement) connection.prepareCall("{?=call " + commandLine + "}");

        cStatement.registerOutParameter(1,
                OracleTypes.ARRAY,
                "BRIDGE.TT_PARAM");

        cStatement.executeUpdate();

        l_array =
                cStatement.getARRAY(1);
        // Получение данных
        Object[] l_Objects = (Object[]) l_array.getArray();

        for (int i = 0; i < l_Objects.length; i++) {
            l_Record = ((STRUCT) l_Objects[i]).getAttributes();
            if (l_Record[1] != null)
                l_prop.put((String) l_Record[0], (String) l_Record[1]);

        }
        return l_prop;
    }

}
